 /**
  * app.js
  *@author Box(wxw113147088@163.com)
  *@date 2019-11-20 9:23
  *@webSite 
  */
const app = require('express')();
const responseTime = require('response-time');
const assert = require("assert");
const StatsD = require('node-statsd');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const config = require('./config/index');
const CookieParser = require("cookie-parser");
const cors = require('cors');

app.use(bodyParser.json());
// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('dev'));
// 中间件
app.use(CookieParser());

// app.use(
//   cors({
//     origin: ["http://127.0.0.1:8080", "http://127.0.0.1:3000"], //指定接收的地址
//     methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //指定接收的请求类型
//     alloweHeaders: ["Content-Type", "Authorization"] //指定header
//     credentials: true,
//   })
// );

//设置CORS
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin','http://127.0.0.1:8080'); //当允许携带cookies此处的白名单不能写’*’
    res.header('Access-Control-Allow-Headers','content-type,Content-Length, Authorization,Origin,Accept,X-Requested-With'); //允许的请求头
    res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT'); //允许的请求方法
    res.header('Access-Control-Allow-Credentials',true);  //允许携带cookies
    next();
});

// app.all("*", (req, res, next) => {
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By", " 3.2.1");
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next();
// });


// 需要跨域的url
// let allowOrigin = [
//     "http://127.0.0.1:8080/",
//     "http://127.0.0.1:3000/"
// ];

// app.use((request, response, next) => {
//     let {origin} = request.headers;
//     if(allowOrigin.includes(origin)) {
//         response.setHeader("Access-Control-Allow-Origin", origin);
//         response.setHeader("Access-Control-Allow-Credentials", true);
//         response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");
//         response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, HEAD, DELETE, OPTIONS");
//         response.setHeader("X-Powered-By", "3.2.1");
//         if(request.method.toUpperCase() == "OPTIONS") {
//             response.statusCode = 204;
//             response.end();
//         }
//     }
//     next();
// });

// 设置端口
app.set('port', (process.env.PORT || 3000));
let stats = new StatsD();
// 使用请求计时模块
// app.use(responseTime((req, res, time) => {
//    var stat = (req.method + req.url)
//      .toLowerCase()
//      .replace(/[:.]/g, "")
//      .replace(/\//g, "_");
//    stats.timing(stat, time);
//    console.log(stats)
// }));
app.use(responseTime());

// 设置/routes/index文件为总的路由控制文件
// 在routes/index文件中再进行统一的路由分发，这样防止app.js中代码过于臃肿
let routes = require('./routes/index');
routes(app);
// 连接MongoDB数据库
mongoose.Promise = global.Promise;
mongoose.set("useNewUrlParser", true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect(config.dbURI);

// 启动服务的时候监听端口号
app.listen(app.get('port'), () => {
  console.log('App listening on port 3000!');
});
